﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Collections;
using PRScreenWithKinect.Model;
using System.Windows.Media.Effects;
using System.Threading;

namespace PRScreenWithKinect
{
    /// <summary>
    /// Interaction logic for Gallery.xaml
    /// </summary>
    public partial class Gallery : UserControl, UserControlInterfaceForGesture
    {
        enum Catagory
        {
            All, Activity=1, Study=2, Achievement=3
        }


        private ArrayList controllerElement;
        private ArrayList _listAlbums;
        private Grid prevMenu;
        private UIElement hitElement = null;
        private UIElement hittedElement = null;
        private Double focusOpacity = 0.7, defaultOpacity = 0.3;
        private SolidColorBrush focusColor = Brushes.Orange, defaultColor = Brushes.White;
        private int pageIndex = 0;
        private int albumPageIndex = 0;
        private int pictureIndex = 0;
        private int mainController;
        private GalleryModel album;
        public Gallery()
        {
            this.InitializeComponent();
            
            Picture.Visibility = Visibility.Hidden;
            _listAlbums = new ArrayList();

            // Add Menu to controllerElement ;s
            controllerElement = new ArrayList();
            controllerElement.Add(Menu1);
            controllerElement.Add(Menu2);
            controllerElement.Add(Menu3);
            controllerElement.Add(Menu4);
            controllerElement.Add(CloseZoom);
           
            mainController = controllerElement.Count;


            // Set Hit Element = menu1 ;
            hittedElement = Menu1;

            // Disable Hittest on object is not use for catagory page
            //CloseZoom.IsHitTestVisible = false;
            //AlbumBack.IsHitTestVisible = false;

            /// Load Data with Catagory All 
            //loadDataFromJSON(Catagory.All);
           
            Dispatcher.BeginInvoke(new ThreadStart(delegate()
            {
                loadDataFromJSON(Catagory.All);
            }));
            ////new Thread(
            //delegate()
            //{
               
            //}).Start();


        }

        private void CloseZoom_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            // TODO: Add event handler implementation here.
            Picture.Visibility = Visibility.Hidden;
          
        }

        private void TextBlock_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            // TODO: Add event handler implementation here.
          

            CatagoryPanel.Visibility = Visibility.Visible;
        }

        private void Rectangle_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            // TODO: Add event handler implementation here.
            Picture.Visibility = Visibility.Visible;
           
        }

        private void StackPanel_MouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            // TODO: Add event handler implementation here.
     
            CatagoryPanel.Visibility = Visibility.Hidden;
        }

  
            public void finishHold()
        {
            //Console.WriteLine("Finish element type " + hitElement.GetType());

            if(hitElement.Equals(Menu1))
            {
                loadDataFromJSON(Catagory.All);
            }else if(hitElement.Equals(Menu2)){
                loadDataFromJSON(Catagory.Activity);
            }
            else if (hitElement.Equals(Menu3))
            {
                loadDataFromJSON(Catagory.Study);
            }
            else if (hitElement.Equals(Menu4))
            {
           //     Console.WriteLine("Finished at MENU4");
                loadDataFromJSON(Catagory.Achievement);
            }
            else if (hitElement.GetType() == typeof(DataGrid))
            {

                DataGrid d = (DataGrid)hitElement;
                album = (GalleryModel)d.DataContext;
                zoomContent(0);
            }
           else if (hitElement.Equals(CloseZoom))
            {
                closeZoom();
            }
  
            hittedElement = hitElement;
            hitElement = null;
        }

         
        public void zoomContent(int i)
        {
            // throw new NotImplementedException();
            /// Remove All Children from Picture
            PictureView.Children.Clear();
            pictureIndex = i;
       //     Console.WriteLine("Picture index : " + (i));
            seqText.Text = album.name + " | " + (pictureIndex + 1) + "/" + album.images_list.Count;
 
            foreach (BitmapImage b in album.images_list)
            {
                //Border border = new Border();
                //border.Background = new ImageBrush(b);
                Image mirror = new Image();
                mirror.Source = b;
                mirror.Width = 548;
                mirror.Height = 365;
                //
                mirror.OpacityMask = new LinearGradientBrush(new GradientStopCollection(new GradientStop[]{
                    new GradientStop(Colors.Transparent,0.494),
                    new GradientStop(Colors.White,1)
                }), new Point(0.5, 0), new Point(0.5, 1));
                mirror.Opacity = 0.5;
                 mirror.Margin = new Thickness(0,3 , 0, 0);
                 mirror.RenderTransform = new ScaleTransform(1,-1,548,182);
                StackPanel t = new StackPanel();
                t.Children.Add(mirror);

                Image img = new Image();
                img.Source = b; 
                img.Height = 365 ;
                img.Width =548 ;

                StackPanel can = new StackPanel();
                can.Height = 730;
                can.Orientation = Orientation.Vertical;
                //can.Background = Brushes.Violet;
               
                can.Children.Add(img);
                can.Children.Add(t);

                PictureView.Children.Add(can);
            }
           
            ZoomView.ScrollToPositionWithoutAnimate( 548 * i,0);
       
            CatagoryPanel.Visibility = Visibility.Hidden;
            Picture.Visibility = Visibility.Visible;

        }

        public void closeZoom()
        {
   
            Picture.Visibility = Visibility.Hidden;
            CatagoryPanel.Visibility = Visibility.Visible;
        }
        //public void closeAlbum()
        //{
        //    controllerElement.Reverse();
        //    controllerElement.RemoveRange(0, album.images.Count);
        //    controllerElement.Reverse();
        //    Album.Visibility = Visibility.Hidden;
        //    Picture.Visibility = Visibility.Hidden;
        //    CatagoryPanel.Visibility = Visibility.Visible;
        //    //Menu1.IsHitTestVisible = true;
        //    //Menu2.IsHitTestVisible = true;
        //    //Menu3.IsHitTestVisible = true;
        //    //Menu4.IsHitTestVisible = true;
        //}
        void loadDataFromJSON(Catagory c)
        {
            //// Remove all data from controllerElement 
            if (prevMenu != null)
            {
                ((Path)prevMenu.Children[0]).Fill = defaultColor;
                controllerElement.RemoveRange(mainController, controllerElement.Count - mainController);
                viewer.Children.RemoveRange(0, viewer.Children.Count);
                pageIndex = 0;
                //controllerElement=  controllerElement.GetRange(0, mainController);
            }
            if (c == Catagory.All)
            {
                prevMenu = Menu1;

            }
            else if (c == Catagory.Activity)
            {
                prevMenu = Menu2;
            }
            else if (c == Catagory.Study)
            {
                prevMenu = Menu3;
            }
            else if (c == Catagory.Achievement)
            {
                prevMenu = Menu4;
        //        Console.WriteLine("Select Gallery : Menu 4");
            }

            ((Path)prevMenu.Children[0]).Fill = focusColor;


          
       //     AlbumModel[] albums = new AlbumModel[numOfAlbum];

          GalleryModel[] gallerys = DataFactory.Instance.getGalleryModelByCatagory((int)c).ToArray();
         
            int numOfAlbum = gallerys.Length;
            double pageNum = Math.Ceiling(numOfAlbum / 9.0);
            double columnNum = pageNum * 3;
          
           for (int i = 0; i < columnNum; i++)
           {
               ColumnDefinition col = new ColumnDefinition();
               col.Width = new GridLength(156);
               viewer.ColumnDefinitions.Add(col);

           }

         //  string pic_url = "http://a6.sphotos.ak.fbcdn.net/hphotos-ak-ash4/s320x320/425737_3281330748318_1119055840_33160134_395247328_n.jpg";


            //// Original Code before use thread 
           for (int i = 0; i < numOfAlbum; i++)
           {
               //albums[i] = new AlbumModel();
               //albums[i].name = "Test Catagory " + i;
               //albums[i].coverpage = new BitmapImage(new Uri(pic_url));
               //albums[i].images = new ArrayList();
               gallerys[i].images_list = new List<BitmapImage>();
               for (int j = 0; j < gallerys[i].images.Length; j++)
               {
                 gallerys[i].images_list.Add(new BitmapImage(new Uri(gallerys[i].images[j])));
               }
       //        albums[i].coverpage = (BitmapImage)albums[i].images[0];
               gallerys[i].coverpage = new BitmapImage(new Uri(gallerys[i].cover));

               DataGrid d = new DataGrid();
               d.Template = (ControlTemplate)this.Resources["MyCatagoryTemplate"];
               d.DataContext = gallerys[i];

               controllerElement.Add(d);
              // Console.WriteLine("Controller count : " + controllerElement.Count);

               Grid.SetRow(d, (i - 9 * (i / 9)) / 3);
               Grid.SetColumn(d, (i / 9) * 3 + i % 3);
               viewer.Children.Add(d);
           }


        
           createPageBullet((int)pageNum);
            

            }
        private void createPageBullet(int n)
        {
            pageBulletStack.Children.RemoveRange(0, pageBulletStack.Children.Count);
            for (int i = 0; i < n; i++)
            {
                Ellipse myEllipse = new Ellipse();

                // Create a SolidColorBrush with a red color to fill the 
                // Ellipse with.

                myEllipse.Fill = Brushes.Gray;
                if (i == 0)
                {
                    myEllipse.Opacity = focusOpacity;
                }
                else
                {
                    myEllipse.Opacity = defaultOpacity;
                }



                // Set the width and height of the Ellipse.
                myEllipse.Width = 20;
                myEllipse.Height = 20;
                myEllipse.Margin = new Thickness(5, 0, 0, 0);
                //   Console.WriteLine("Add Bullet");
                pageBulletStack.Children.Add(myEllipse);
            }


        }
    

        public void swipeLeft()
        {
            doSwipe(Swipe.Left);


        }

        public void swipeRight()
        {
            doSwipe(Swipe.Right);
        }


        public void doSwipe(Swipe s)
        {

            if (CatagoryPanel.Visibility == Visibility.Visible)
            {
                if (s == Swipe.Left && pageIndex != (Math.Ceiling(viewer.Children.Count / 9.0)-1))
                {
                    pageIndex++;
                    pageBulletStack.Children[pageIndex].Opacity = focusOpacity;
                    pageBulletStack.Children[pageIndex - 1].Opacity = defaultOpacity;

                }
                else if (s == Swipe.Right && pageIndex != 0)
                {

                    pageIndex--;
                    pageBulletStack.Children[pageIndex].Opacity = focusOpacity;
                    pageBulletStack.Children[pageIndex + 1].Opacity = defaultOpacity;

                }
                scrollView.ScrollToPosition(scrollView.Width * pageIndex, 0);
            }
            else if (PictureView.Visibility == Visibility.Visible)
            {
                
                if (s == Swipe.Left && pictureIndex < (album.images_list.Count-1))
                {
                    pictureIndex++;


                }
                else if (s == Swipe.Right && pictureIndex != 0)
                {
                    pictureIndex--;

                }
                seqText.Text = album.name+" | "+ (pictureIndex+1)+"/"+album.images_list.Count;
                ZoomView.ScrollToPosition(ZoomView.Width * pictureIndex, 0);
            }
          
         

             // Console.WriteLine("News(doSwipe) : " + pageIndex);

        }


        public bool hitTest(Point p, Window w)
        {

            Boolean isHit = false;
           // Console.WriteLine("===========================");
            for (int i = (controllerElement.Count - 1); i > -1; i--)
            {
                UIElement c = (UIElement)controllerElement[i];
                Point RhandRelativePoint = c.TransformToAncestor(w).Transform(new Point(0, 0));
                Point delta = new Point(p.X - RhandRelativePoint.X, p.Y - RhandRelativePoint.Y);
                if (VisualTreeHelper.HitTest(c, delta) != null)
                {
                    if (c.Equals(hitElement) && !c.Equals(hittedElement))
                    {

                    //    if (c.GetType() == typeof(DataGrid) || c.Equals(CloseZoom) || c.GetType() == typeof(Image) )
                    //    {
                            if (c.GetType() == typeof(DataGrid) && CatagoryPanel.IsVisible)
                            {
                                return true;
                            }
                             else if ((c.Equals(CloseZoom) ) && Picture.IsVisible)
                            {

                                return true;


                            }
                            else if (Menubar.IsAncestorOf(c)&&CatagoryPanel.IsVisible)
                            {
                                return true;
                            }
                            //else
                            //{
                            //       isHit = false;

                            //}
                     //   return true;
                        
                        //else if (CatagoryPanel.Visibility == Visibility.Visible)
                        //{
                        //    return true;
                        //}
                    }
                    else
                    {


                        hitElement = c;
                        return false;

                    }
                }
            }




            return isHit;
        }
    }


    }
